package github._3y.algorithms;

import java.util.Arrays;

/**
 * @Author: DRevelation
 * @Date: 2021/1/20 19:53
 */
public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = new int[]{3, 1, 5, 2, 4};
        bubbleSort(arr);
        System.out.println("=======================");
        System.out.println("arr = " + Arrays.toString(arr));
    }

    private static void bubbleSort(int[] arr) {
        //临时变量
        int temp;
        //次数
        int num = 0;
        //是否发生置换
        int isChange;

        for (int i = 0; i < arr.length - 1; i++) {
            isChange = 0;
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    isChange = 1;
                }
                System.out.println("arr = " + Arrays.toString(arr));
            }
            if (isChange == 0) {
                break;
            }
            num++;
        }
        System.out.println("执行了" + num + "次");
    }

}
